package com.ustcinfo.study.mr.liuxiaoshuang;

import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

public class MapReducerTest {
	/**
	 * Mapping
	 * @author liu.xiaoshuang
	 */
											   //传入key值，传入value值，输出的key值，输出的value值
	public static class MyMapper extends Mapper<Object, Text, Text, IntWritable> {
		private static final IntWritable count = new IntWritable(1);
		@Override
						   //context监控者，用于中转接收
		protected void map(Object key, Text value, Context context) throws IOException, InterruptedException {
			String line = value.toString();
			String[] arr = line.split(" ");
			for (int i = 0; i < arr.length; i++) {
				Text word = new Text();
				word.set(arr[i]);
				context.write(word, count);
			}
		}
	}
	
	/**
	 * Reducer
	 * @author liu.xiaoshuang
	 */
																	//此处的Text,IntWritable要与map的出参保持一致
	private static class MyReducer extends Reducer<Text, IntWritable, Text, IntWritable> {
		@Override
		protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
			int sum = 0;
			for (IntWritable val : values) {
				sum += val.get();
			}
			context.write(key, new IntWritable(sum));
		}
	}
	
	public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
		Job job = Job.getInstance();
		//工作名
		job.setJobName("sg_word_count");
		//工作的类
		job.setJarByClass(MyMapper.class);
		//map工作的类
		job.setMapperClass(MyMapper.class);
		//reduce工作的类
		job.setReducerClass(MyReducer.class);
		//传出key值的类型
		job.setOutputKeyClass(Text.class);
		//传出value值的类型
		job.setOutputValueClass(IntWritable.class);
		FileInputFormat.addInputPath(job, new Path(args[0]));
		FileOutputFormat.setOutputPath(job, new Path(args[1]));
		int status = job.waitForCompletion(true) ? 0 : 1;
		System.exit(status);
	}
	
}
